<?php
/**
 * Created by PhpStorm.
 * User: WJP
 * Date: 2019-04-13
 * Time: 10:09
 */
#!/bin/env php
/**
 * 定义项目根目录&swoole-task pid
 */
define('SWOOLE_PATH', __DIR__);
define('SWOOLE_LOG_PATH', SWOOLE_PATH . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . 'Swoole' . '.log');

/**
 * 加载 swoole server
 */
include SWOOLE_PATH .  DIRECTORY_SEPARATOR . 'Server.php';

//提示帮助信息
if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
    echo <<<HELP
用法：php swoole.php 选项 ... 可选的命令[start|reload|list]

--help|-help|-h|-?  显示本帮助说明

选项说明
    start,  启动swoole服务[默认监测9501端口]
    reload, 柔性重启所有workder进程
    list,   查看当前所有连接的客户端数

HELP;
    exit;
}

//执行命令行选项
switch($argv[1]){
    case 'start':
        start();
        break;
    case 'reload':
        reload();
        break;
    case 'list':
        clients();
        break;
    default:
        exit("输入命令有误 : {$argv[1]}, 请查看帮助文档\n");
        break;
}

//启动swoole服务
function start(){
    $server = new Server();
    $server->start();
}

//柔性重启swoole服务
function reload(){
    echo "正在柔性重启swoole的worker进程..." . PHP_EOL;
    try {
        $server = new Server();
        $port = $server->getPort();
        $host = '127.0.0.1';
        $cli = new swoole_http_client($host, $port);
        $cli->set(['websocket_mask' => true]);
        $cli->on('message', function ($_cli, $frame) {
            if($frame->data){
                exit('swoole重启成功！'.PHP_EOL);
            }
        });
        $cli->upgrade('/', function ($cli) {
            $cli->push(json_encode(['cmd' => 'reload']));
        });
    } catch (Exception $e) {
        exit($e->getMessage() . PHP_EOL . $e->getTraceAsString());
    }
}

function clients(){
    try {
        $server = new Server();
        $port = $server->getPort();
        $host = '127.0.0.1';
        $cli = new swoole_http_client($host, $port);
        $cli->set(['websocket_mask' => true]);
        $cli->on('message', function ($_cli, $frame) {
            $users = json_decode($frame->data , true);
            if(empty($users)){
                echo '当前没有客户端连接'.PHP_EOL;
            }else{
                foreach($users as $user){
                    echo '---'.$user.PHP_EOL;
                }
            }
            exit();
        });
        $cli->upgrade('/', function ($cli) {
            $cli->push(json_encode(['cmd' => 'clients']));

        });
    } catch (Exception $e) {
        exit($e->getMessage() . PHP_EOL . $e->getTraceAsString());
    }
}
